package com.gosling.cloudspace.config.mybatis;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
public final class PageResult<T> implements Serializable {

    private List<T> list = new ArrayList<>();

    private Long total;

    private Long totalPage;

    private Long pageSize;

    private Long pageNo;

    public PageResult() {
    }

    public PageResult(List<T> list, Long total) {
        this.list = list;
        this.total = total;
    }

    public PageResult(Long total) {
        this.list = new ArrayList<>();
        this.total = total;
    }

    /***
     * mybatisplus 分页结果转换
     *
     * @see Page
     * @param page
     * @return
     */
    public static PageResult result(Page page) {
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setTotalPage(page.getPages());
        result.setPageNo(page.getCurrent());
        result.setList(page.getRecords());
        result.setPageSize(page.getSize());
        return result;
    }

    /***
     * mybatisplus 分页结果转换
     *
     * @see IPage
     * @param page
     * @return
     */
    public static PageResult result(IPage page) {
        if (ObjectUtil.isNull(page)) {
            return null;
        }
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setTotalPage(page.getPages());
        result.setPageNo(page.getCurrent());
        result.setList(page.getRecords());
        result.setPageSize(page.getSize());
        return result;
    }

    public static <T> PageResult<T> empty() {
        return new PageResult<>(0L);
    }

    public static <T> PageResult<T> empty(Long total) {
        return new PageResult<>(total);
    }

}
